#ifdef __cplusplus
extern "C"
{
#endif

#include <ets_sys.h>
#include <osapi.h>
#include <ip_addr.h>
#include <c_types.h>
#include <espconn.h>
#include <user_interface.h>

void user_init(void);
	
#ifdef __cplusplus
}
#endif

#ifdef ESP8266_GDBSTUB
#include <gdbstub.h>
#endif

void dhcps_lease_test(void)
{
	struct dhcps_lease dhcp_lease;
	IP4_ADDR(&dhcp_lease.start_ip, 192, 168, $$com.sysprogs.esp8266.http.subnet$$, 100);
	IP4_ADDR(&dhcp_lease.end_ip, 192, 168, $$com.sysprogs.esp8266.http.subnet$$, 105);
	wifi_softap_set_dhcps_lease(&dhcp_lease);
}

static char s_ReplyFormat[] = "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n<html><body><h1>Hello, World</h1>This page was generated by your ESP8266 device %d times.</body></html>";
static char s_Reply[sizeof(s_ReplyFormat) + 20];
static int s_RequestNumber;

static void __attribute__((section(".irom.text"))) httpdConnectCb(void *arg) 
{
	struct espconn *pConn = (struct espconn*)arg;
	os_sprintf(s_Reply, s_ReplyFormat, ++s_RequestNumber);
	espconn_sent(pConn, (uint8_t *)s_Reply, strlen(s_Reply));
	
	espconn_disconnect(pConn);
}

/*
	How to use this example:
		1. Build & program it to your ESP8266
		2. Connect to the $$com.sysprogs.esp8266.http.ssid$$ WiFi network from your computer
		3. Open http://192.168.$$com.sysprogs.esp8266.http.subnet$$.1/ in your browser
*/

void user_init()
{
#ifdef ESP8266_GDBSTUB
	gdbstub_init();
#endif

	//Uncomment the line below if you want to step through the initialization function in the debugger without getting a reset from a watchdog.
	//system_soft_wdt_stop();
	struct ip_info info;
	struct softap_config cfg;
	wifi_softap_get_config(&cfg);
	strcpy((char *)cfg.ssid, "$$com.sysprogs.esp8266.http.ssid$$");
	cfg.ssid_len = strlen((char*)cfg.ssid);
	wifi_softap_set_config_current(&cfg);
	wifi_set_opmode(SOFTAP_MODE);
	
	wifi_softap_dhcps_stop();
	IP4_ADDR(&info.ip, 192, 168, $$com.sysprogs.esp8266.http.subnet$$, 1);
	IP4_ADDR(&info.gw, 192, 168, $$com.sysprogs.esp8266.http.subnet$$, 1);
	IP4_ADDR(&info.netmask, 255, 255, 255, 0);
	wifi_set_ip_info(SOFTAP_IF, &info);
	dhcps_lease_test();
	wifi_softap_dhcps_start();
	
	static struct espconn httpdConn;
	static esp_tcp httpdTcp;
	httpdConn.type = ESPCONN_TCP;
	httpdConn.state = ESPCONN_NONE;
	httpdTcp.local_port = 80;
	httpdConn.proto.tcp = &httpdTcp;

	espconn_regist_connectcb(&httpdConn, httpdConnectCb);
	espconn_accept(&httpdConn);
}
